﻿<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>全选练习</title>
	<script>
			//js代码设置网页加载完毕后再加载js代码
		window.onload = function () {
			//获取按钮并在js中用赋值给变量
			var allButtom = document.getElementById('checkedAllBtn');
			//用getElementsByName获取表单中的复选框   注意返回的是一个数组
			var items = document.getElementsByName('items');
			function select(btn,boolean){
				var btn = document.getElementById('btn');
				btn.onclick =function () {
					for (var i in items){
						items[i].checked = boolean;
					}
				}
			}
			//设置单击响应函数
			allButtom.onclick = function () {
				//遍历数组,并设置复选框为选中状态
				for (var i in items){
					items[i].checked = true;
				}
			}
			//全不选按钮,同样获取按钮
			var checkedNoBtn = document.getElementById('checkedNoBtn');
			//设置单击响应函数,遍历,然后设置复选框属性为false
			checkedNoBtn.onclick = function () {
				for (var i in items){
					items[i].checked = false;
				}
			}
			//设置反选
			var checkedRevBtn = document.getElementById('checkedRevBtn');
			checkedRevBtn.onclick = function(){
				for (var i in items){
					items[i].checked = !items[i].checked;
				}
			}
			//设置复选框
			var checkedAllBox = document.getElementById('checkedAllBox');
			//设置单击响应函数

			// function fn (){
			// 	var j = 0;
			// 	inner = function () {
			// 		if ( j === 0){
			// 			for ( var i in items){
			// 				items[i].checked = true;
			// 			}
			// 			j = 1;
			// 		}else if (j === 1){
			// 			for ( var i in items){
			// 				items[i].checked = false;
			// 			}
			// 			j = 0;
			// 		}
			// 	}
			// 	return inner;
			// }
			// checkedAllBox.onclick = fn();

			//--------分割线-----   去除闭包

				var j = 0;
			checkedAllBox.onclick = function () {
					if ( j === 0){
						for ( var i in items){
							items[i].checked = true;
						}
						j = 1;
					}else if (j === 1){
						for ( var i in items){
							items[i].checked = false;
						}
						j = 0;
					}
				}


			// checkedAllBox.onclick = fn();
			//设置提交按钮
			var sendBtn = document.getElementById('sendBtn');
			sendBtn.onclick = function () {
				alert('数据已经提交!');
			}
		}

	</script>
</head>
<body>

	<form method="post" action="">
		你爱好的运动是？<input type="checkbox" id="checkedAllBox" />全选/全不选 
		
		<br />
		<input type="checkbox" name="items" value="足球" />足球
		<input type="checkbox" name="items" value="篮球" />篮球
		<input type="checkbox" name="items" value="羽毛球" />羽毛球
		<input type="checkbox" name="items" value="乒乓球" />乒乓球
		<br />
		<input type="button" id="checkedAllBtn" value="全　选" />
		<input type="button" id="checkedNoBtn" value="全不选" />
		<input type="button" id="checkedRevBtn" value="反　选" />
		<input type="button" id="sendBtn" value="提　交" />
	</form>
</body>
</html>